package com.binvshe.binvshe.message.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.app.home.ClassEvent;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.message.MessageType;
import com.binvshe.binvshe.message.dao.Message;
import com.binvshe.binvshe.message.dao.MessageHelper;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 */
public class OtherMessageFragment extends SwipeListFragment {

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new OtherMessageListAdapter(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        setPullToRefreshEnable(false);
        setAutoLoading(false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        reload();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        reload();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(ClassEvent.RefreshEvent refreshEvent) {
        getMessageData();
    }

    @Override
    public void onStartLoading() {
        getMessageData();
    }

    public void getMessageData() {
        List<Message> mMessageLis = MessageHelper.getInstance().loadMessage(MessageType.MSG_TYPE_INVITE,
                MessageType.MSG_TYPE_REQUEST, MessageType.MSG_TYPE_OTHERS ,MessageType.MSG_TYPE_CLUB);
        if (mMessageLis.size() <= 0) {
            setState(CompState.EMPTY);
        } else {
            setState(CompState.DATA);
            getAdapter().getData().clear();
            getAdapter().getData().addAll(mMessageLis);
            getAdapter().notifyDataSetChanged();
        }
    }

    void reload() {
        getAdapter().getData().clear();
        getAdapter().notifyDataSetChanged();
        startLoading();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long itemId) {

        final AlertDialogFragment dialogFragment = new AlertDialogFragment();
        dialogFragment.setTitle("删除消息")
                .setMessage("确定删除？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Message msg = (Message) getData().get(position);
                        MessageHelper.getInstance().getMsgDao().delete(msg);
                        reload();
                        dialogFragment.dismissAllowingStateLoss();

                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialogFragment.dismissAllowingStateLoss();
                    }
                }).show(getFragmentManager());

        return true;
    }


    public class OtherMessageListAdapter extends RecyclerViewBaseAdapter<Message> {


        public OtherMessageListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            switch (viewType) {
                //有button布局
                case MessageType.MSG_TYPE_INVITE:
                case MessageType.MSG_TYPE_REQUEST:
                    return new VHWithBtn(setAdapterViewItem(parent, R.layout.item_other_message_btn));
                default:
                    return new VH(setAdapterViewItem(parent, R.layout.item_other_message));
            }
        }

        @Override
        public int getItemViewType(int position) {
            return getData().get(position).getType();
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final Message message = getData().get(position);
            if (holder instanceof VHWithBtn) {
                final VHWithBtn viewHolder = (VHWithBtn) holder;
                if (!TextUtils.isEmpty(message.getIcon()))
                    IML.load(getContext(), viewHolder.mImgHead, message.getIcon());
                if (!TextUtils.isEmpty(message.getTitle()))
                    viewHolder.mTvTitle.setText(message.getTitle());
                if (!TextUtils.isEmpty(message.getContent()))
                    viewHolder.mTvContent.setText(message.getContent());
                if (message.getIsRead()) {
                    viewHolder.mImgPoint.setVisibility(View.GONE);
                } else {
                    viewHolder.mImgPoint.setVisibility(View.VISIBLE);
                }

                String extraMessage = message.getExtra();
                try {
                    JSONObject extraJobj = new JSONObject(extraMessage);

                    final int id = extraJobj.optInt("id");
                    final int clubId = extraJobj.optInt("target_id");

                    if (message.getType() == MessageType.MSG_TYPE_REQUEST) {
                        viewHolder.mBtnAgree.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                sendRequestAgree(clubId, id, message);
                            }
                        });
                        viewHolder.mBtnRefuse.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                sendRequestRefuse(clubId, id, message);
                            }
                        });
                    } else if (message.getType() == MessageType.MSG_TYPE_INVITE) {
                        viewHolder.mBtnAgree.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                sendInvitAgree(clubId, id, message);
                            }
                        });
                        viewHolder.mBtnRefuse.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                sendInvitRefuse(clubId, id, message);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (holder instanceof VH) {
                final VH viewHolder = (VH) holder;
                if (!TextUtils.isEmpty(message.getIcon()))
                    IML.load(getContext(), viewHolder.mImgHead, message.getIcon());
                if (!TextUtils.isEmpty(message.getTitle()))
                    viewHolder.mTvTitle.setText(message.getTitle());
                if (!TextUtils.isEmpty(message.getContent()))
                    viewHolder.mTvContent.setText(message.getContent());
                if (message.getIsRead()) {
                    viewHolder.mImgPoint.setVisibility(View.GONE);
                } else {
                    viewHolder.mImgPoint.setVisibility(View.VISIBLE);
                }
                viewHolder.mTvContent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setIsReadView(getData().get(position));
                        EasyToast.showToast(getContext(), message.getContent());
                    }
                });
            }
        }

        private void sendRequestRefuse(int clubId, final int id, final Message message) {
            MyHttpRequest request = new MyHttpRequest(getContext());
            String url = String.format(UrlCenter.REFUSE_REQUEST, clubId, id);
            request.put(url, null, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    MessageHelper.getInstance().deleteMessage(message);
                    getData().remove(message);
                    notifyDataSetChanged();
                    EasyToast.showToast(getContext(), "已拒绝");
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getContext(), strMsg);
                }
            });
        }

        private void sendRequestAgree(int clubId, final int id, final Message message) {
            MyHttpRequest request = new MyHttpRequest(getContext());
            String url = String.format(UrlCenter.AGREE_REQUEST, clubId, id);
            request.put(url, null, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    MessageHelper.getInstance().deleteMessage(message);
                    getData().remove(message);
                    notifyDataSetChanged();
                    AccountManager.getCurrentAccount().setInClub(true);
                    EasyToast.showToast(getContext(), "已同意");
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    if (errorNo != -1) {
                        EasyToast.showToast(getContext(), strMsg);
                    } else {
                        MessageHelper.getInstance().deleteMessage(message);
                        getData().remove(message);
                        notifyDataSetChanged();
                    }
                }
            });
        }

        private void sendInvitAgree(int clubId, int id, final Message message) {
            MyHttpRequest request = new MyHttpRequest(getContext());
            String url = String.format(UrlCenter.AGREE_INVITE, clubId, id);
            request.put(url, null, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    MessageHelper.getInstance().deleteMessage(message);
                    getData().remove(message);
                    notifyDataSetChanged();
                    EasyToast.showToast(getContext(), "已同意");
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getContext(), strMsg);
                }
            });
        }

        private void sendInvitRefuse(int clubId, int id, final Message message) {
            MyHttpRequest request = new MyHttpRequest(getContext());
            String url = String.format(UrlCenter.REFUSE_INVITE, clubId, id);
            request.put(url, null, new DataRequestListener<String>(String.class) {
                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(String o) {
                    super.onSuccess(o);
                    MessageHelper.getInstance().deleteMessage(message);
                    getData().remove(message);
                    notifyDataSetChanged();
                    EasyToast.showToast(getContext(), "已拒绝");
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(getContext(), strMsg);
                }
            });
        }

        private void setIsReadView(Message message) {
            message.setIsRead(true);
            MessageHelper.getInstance().updataIsRead(message);
        }

        public class VHWithBtn extends RecyclerView.ViewHolder {

            @Bind(R.id.mImgHead)
            CircleImageView mImgHead;
            @Bind(R.id.mTvTitle)
            TextView mTvTitle;
            @Bind(R.id.mTvContent)
            TextView mTvContent;
            @Bind(R.id.mBtnAgree)
            Button mBtnAgree;
            @Bind(R.id.mBtnRefuse)
            Button mBtnRefuse;
            @Bind(R.id.mTvResult)
            TextView mTvResult;
            @Bind(R.id.mImgPoint)
            ImageView mImgPoint;

            public VHWithBtn(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.mImgHead)
            CircleImageView mImgHead;
            @Bind(R.id.mTvTitle)
            TextView mTvTitle;
            @Bind(R.id.mTvContent)
            TextView mTvContent;
            @Bind(R.id.mImgPoint)
            ImageView mImgPoint;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
